//二次封装axios
import axios from "axios"
//导入store，取出token的值 进行验证
import { store } from "../store"
import { createBrowserHistory } from "history"
import { notification } from "antd"

var history = createBrowserHistory()


//实例化axios
var service = axios.create({
    timeout: 10 * 1000,//超时时间
    baseURL: process.env.REACT_APP_BASE_API//基准路径
    // baseURL: ''
})

//设置请求拦截器
service.interceptors.request.use(
    (config) => {
        config.headers['token'] = store.getState().userinfo.token;
        return config;
    },
    (error) => {
        return Promise.reject(error)
    }
)

//设置响应拦截器
service.interceptors.response.use(
    (res) => {
        // if (res.data.code == '10119') {
        //     //token无效
        //     store.dispatch({ type: 'REMOVE_USERINFO' })//清除token
        //     history.push('/login')
        //     history.go(0)
        // }
        return res
    },
    (error) => {
        if (error.response.status == 401) {
            notification.error({ message: '登录过期' })
            store.dispatch({ type: 'REMOVE_USERINFO' })//清除token
            history.push('/login')
            history.go(0)
        } else if (error.response.status == 404) {
            notification.error({ message: '访问路径有误' })
        }
        else if (error.response.status == 500) {
            notification.error({ message: '服务器内部错误' })
        }
        else if (error.response.status == 503) {
            notification.error({ message: '服务器不可用' })
        }
        return Promise.reject(error)
    }
)

export default service;